﻿using System.Collections.Generic;
using System.Management;

namespace Labthink.PCSoft.UniversalHost4.Utility
{
    public static class IoUtility
    {
        public static List<UDiskInfo> GetDrivers()
        {
            var drivers = new List<UDiskInfo>();
            const string strQuery = "select * from Win32_DiskDrive Where InterfaceType = 'USB'";
            //else if (type == InterfaceType.IDE)
            //    strQuery += " Where InterfaceType = 'IDE'";

            var sq = new SelectQuery(strQuery);
            var mos = new ManagementObjectSearcher(sq);
            foreach (var disk in mos.Get())
            {
                string deviceId = disk["DeviceID"].ToString();
                foreach (var partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + deviceId + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
                {
                    string query = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition";
                    foreach (var disk1 in new ManagementObjectSearcher(query).Get())
                    {
                        var b = new UDiskInfo();
                        string diviceId = disk1["DeviceID"].ToString().Trim();

                        string name = disk1["Name"].ToString().Trim();
                        string freeSpace = disk1["FreeSpace"].ToString().Trim();
                        string size = disk1["Size"].ToString().Trim();
                        string vname = disk1["VolumeName"].ToString();

                        b.Id = diviceId;
                        b.Name = name;
                        b.Total = double.Parse(size);
                        b.Usable = double.Parse(freeSpace);
                        b.VName = vname;
                        drivers.Add(b);
                    }
                }
            }
            return drivers;
        }
    }

    public class UDiskInfo
    {
        public string Id { get; set; }

        /// <summary>
        /// U盘名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 卷标
        /// </summary>
        public string VName { get; set; }

        /// <summary>
        /// 总容量（M）
        /// </summary>
        public double Total { get; set; }

        /// <summary>
        /// 可用容量
        /// </summary>
        public double Usable { get; set; }
    }
}
